package com.gitee.free.coding.admin.system.controller;

import com.gitee.free.coding.admin.system.req.SystemLoginReq;
import com.gitee.free.coding.admin.system.res.body.SystemLoginResBody;
import com.gitee.free.coding.admin.system.res.body.SystemVerificationCodeResBody;
import com.gitee.free.coding.admin.system.service.ISystemUserAuthService;
import com.gitee.free.coding.core.utils.EmptyData;
import com.gitee.free.coding.core.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liaoen
 * @since 2024-05-29 22:44:05
 */
@RestController
@RequestMapping("/system/systemUserAuth")
public class SystemUserAuthController {

    @Autowired
    private ISystemUserAuthService systemUserAuthService;

    @GetMapping("/captcha")
    public Result<SystemVerificationCodeResBody> captcha() {
        SystemVerificationCodeResBody systemVerificationCodeResBody = systemUserAuthService.generateVerificationCode();
        return Result.success(systemVerificationCodeResBody);
    }

    @PostMapping("/register")
    public Result<EmptyData> register(@RequestBody SystemLoginReq systemLoginReq) {
        systemUserAuthService.register(systemLoginReq);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<SystemLoginResBody> login(@RequestBody SystemLoginReq systemLoginReq, HttpServletRequest request) {
        if (systemLoginReq == null) {
            systemLoginReq = new SystemLoginReq();
        }
        // TODO 后续修改
        // String userAgent = request.getHeader("User-Agent");
        String userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36";
        // LoginAspect 拦截器中处理 userAgent
        systemLoginReq.setUserAgent(userAgent);
        systemLoginReq.setIpAddress(getIpAddress(request));
        SystemLoginResBody systemLoginResBody = systemUserAuthService.login(systemLoginReq);
        return Result.success(systemLoginResBody);
    }

    private String getIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }

}
